﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Accountant.DataModel;
using Accountant.Utils;

namespace Accountant.Primitives
{
  public class MoneyBag : ReadOnlyCollection<Money>
  {
    public MoneyBag(IEnumerable<Money> money)
      : base(money.ToArray())
    {
    }
    public decimal this[Currency index]
    {
      get
      {
        var m = this.FirstOrDefault(c => c.Currency.Id == index.Id);
        return m == null ? 0 : m.Amount;
      }
    }
    public static MoneyBag operator -(MoneyBag x)
    {
      return new MoneyBag(x.Select(m => new Money(m.Currency, -m.Amount)));
    }
    public static MoneyBag operator -(MoneyBag x, MoneyBag y)
    {
      return x + (-y);
    }
    public static MoneyBag operator +(MoneyBag x, MoneyBag y)
    {
      return new MoneyBag(x
        .Concat(y)
        .GroupBy(m => m.Currency)
        .Select(g => g.Sum())
        .Where(m => m.Amount != 0));
    }
  }
}
